import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';
import 'DriverIntroduction.dart';
import 'package:platform/platform.dart';

import 'SelectSourceOfGoods.dart';
class MyFamiliarCar extends StatefulWidget {
  const MyFamiliarCar({super.key});

  @override
  State<MyFamiliarCar> createState() => _MyFamiliarCarState();
}

class _MyFamiliarCarState extends State<MyFamiliarCar> {
  List dataList=[];
  bool isLoading =false;
  int pageNum=1;
  String searchPhone="";
  String searchVel="";
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();

  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });

    getMyDriversAction("","");
    super.initState();
  }

  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }


 void deleFamiliarCarAction(String id) async {
    String? token = await TokenManager.getToken();

    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header+'api/user/shipper/driver/delete',
      data: [{
        "id":id,
      }],
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 5),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          BrnToast.show(
            "移除成功",
            context,
            duration: BrnDuration.short,
          );
          getMyDriversAction("","");
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }

  void getMyDriversAction(String phoneNum,String vehicleNum) async {
    String? ShipperId = await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/shipper/driver/page', // 您的API端点
      {"shipperId":ShipperId,"current":pageNum,"size":20,"phoneNum":searchPhone,"vehicleNum":searchVel}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          if(pageNum==1) {
            dataList = responseData['data']['records'];
          }else{
            if(responseData['data']['records'].isNotEmpty){
              dataList.addAll(responseData['data']['records']);
            }else{
              pageNum=pageNum-1;
            }
          }
        });

      },
    );
  }



void _onRefresh(){
    pageNum=1;
  getMyDriversAction("","");
}
void _loadMoreData(){
    if(dataList.length>20*pageNum-1){
      pageNum=pageNum+1;
      getMyDriversAction("","");
    }
}
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Container(
      child: ListView(
        children: [
          Container(
            height:40.h,
            child:   BrnSearchText(
              focusNode: focusNode,
              controller: textController,
              searchController: scontroller..isActionShow = false,
              outSideColor: MyColors.backgreyColor,
              innerColor: Colors.white,
              borderRadius: BorderRadius.all(const Radius.circular(10.0)),
              hintText: "输入司机手机号码/车牌号",
              onTextClear: () {
                debugPrint('sss');
                return false;
              },
              autoFocus: false, // 将这里设置为 false 来关闭自动获取焦点
              onActionTap: () {
                scontroller.isClearShow = false;
                scontroller.isActionShow = false;
                focusNode.unfocus();
              },
              onTextCommit: (text) {
              },
              onTextChange: (text) {
                if (text.contains(RegExp(r'[a-zA-Z]')) && text.length > 0) {
                  setState(() {
                    searchVel=text;
                  });
                  getMyDriversAction("",text);
                } else {
                  setState(() {
                    searchPhone=text;
                  });
                  getMyDriversAction(text, "");
                }
              },
            ),
          ),


          Container(

            color: Colors.white,
            height: screenSize.height-180.h,
            child:EasyRefresh(
                header:  ClassicHeader(
              dragText: '下拉刷新',
              armedText: '准备释放',
              readyText: '加载中...',
              processingText: '加载中...',
              processedText: '刷新成功',
              noMoreText: '暂无更多',
              failedText: '刷新失败',
              messageText: '刷新时间 %T',
            ),

              footer: ClassicFooter(
                dragText: '加载更多',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '加载成功',
                noMoreText: '暂无更多',
                failedText: '加载失败',
                messageText: '加载时间 %T',
              ),
              onRefresh: _onRefresh,
              onLoad: dataList.length > 20*pageNum-1?_loadMoreData:null,
            child:
            ListView(
              children: [
            dataList.length==0?BrnAbnormalStateWidget(
                img: Image.asset(
                  'lib/Images/OrderList/发货中暂无货源.png',
                  scale: 3.0,
                ),
                content: '暂无熟车',

            ):Container(
              height: screenSize.height-180.h,
              color: MyColors.backgreyColor,
              child: ListView.builder(
                  shrinkWrap:false,
                  itemCount:dataList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      child:    Container(
                        decoration: BoxDecoration(
                            color:Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        margin: EdgeInsets.only(left: 10.w,right: 10.w,bottom: 8.h),
                        padding: EdgeInsets.only(left:15.w,right: 15.w,top: 10.h,bottom: 10.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.all(Radius.circular(10))),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.all(Radius.circular(10)),
                                        child: dataList[index]['avatarPath']!=""&&dataList[index]['avatarPath']!=null?Image.network(
                                          MyServiceUrl.imgHeader + dataList[index]['avatarPath'],
                                          width: 36.w,
                                          height: 36.h,
                                          fit: BoxFit.cover,
                                        ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                      ),
                                    ),
                                    SizedBox(width: 8.w,),
                                    if(dataList[index]['realName']!=null)
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                        Text(maskPhoneNumber(dataList[index]['phoneNum']),style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                                      ],
                                    ),

                                  ],
                                ),
                                if(dataList[index]['personalStatus']!=null)
                                if(dataList[index]['personalStatus']==2&&dataList[index]['driverLicenseStatus']==2&&dataList[index]['vehicleDrivingLicenseStatus']==2
                                    &&(dataList[index]['qualificationCertificateStatus']!=2||dataList[index]['roadTransportCertificateStatus']!=2))
                                  BrnTagCustom.buildBorderTag(
                                    tagText: '三证齐全',
                                    textColor: MyColors.themeColor,
                                    borderColor: MyColors.themeColor,
                                    borderWidth: 1.w,
                                    fontSize: 11.sp,
                                  ),
                                if(dataList[index]['personalStatus']!=null)
                                if(dataList[index]['personalStatus']==2&&dataList[index]['driverLinsenseStatus']==2&&dataList[index]['vehicleDrivingLisenseStatus']==2
                                    &&dataList[index]['qualificationCertificateStatus']==2&&dataList[index]['roadTransportCertificateStatus']==2)
                                  BrnTagCustom.buildBorderTag(
                                    tagText: '五证齐全',
                                    textColor: MyColors.themeColor,
                                    borderColor: MyColors.themeColor,
                                    borderWidth: 1.w,
                                    fontSize: 11.sp,
                                  ),
                              ],
                            ),
                            SizedBox(height: 4.h,),
                            Text(dataList[index]['vehicleNum']!=null?dataList[index]['vehicleNum']:"",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                            SizedBox(height: 4.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                if(dataList[index]['vehicleLength']!=null)
                                Row(
                                  children: [
                                    Text(dataList[index]['vehicleLength']+"丨"+dataList[index]['vehicleModel']+"丨"+dataList[index]['vehicleTonnage']+"吨",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),)
                                  ],
                                ),
                                // RichText(
                                //   text: TextSpan(
                                //     text: '好评率 ', // 第一部分文本
                                //     style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),
                                //     children: [
                                //       TextSpan(
                                //         text: dataList[index]['driverReview']!=null?'100%':"暂无评价", // 第二部分文本
                                //         style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
                                //       ),
                                //     ],
                                //   ),
                                // ),
                              ],
                            ),
                            Divider(
                              height: 10.h,
                              color: MyColors.backgreyColor,
                            ),
                            Container(
                              height:30.h,
                              child:  Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  GestureDetector(
                                    child:  BrnTagCustom.buildBorderTag(
                                      tagText: '立即派单',
                                      textColor: MyColors.themeColor,
                                      borderColor: MyColors.themeColor,
                                      fontWeight: FontWeight.w600,
                                      borderWidth: 1,
                                      fontSize: 12.sp,
                                      tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                      textPadding: EdgeInsets.all(6),
                                    ),
                                    onTap: (){
                                      Navigator.push( context, FadeRoute(page:SelectSourceOfGoods(carMap:dataList[index],)));
                                    },
                                  ),
                                  SizedBox(width: 8.w,),
                                  GestureDetector(
                                    child:  BrnTagCustom.buildBorderTag(
                                      tagText: '移除熟车',
                                      textColor: MyColors.themeColor,
                                      borderColor: MyColors.themeColor,
                                      fontWeight: FontWeight.w600,
                                      borderWidth: 1,
                                      fontSize: 12.sp,
                                      tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                      textPadding: EdgeInsets.all(6),
                                    ),
                                    onTap: (){
                                      deleFamiliarCarAction(dataList[index]['driverId']);
                                    },
                                  ),
                                  SizedBox(width: 8.w,),
                                  GestureDetector(
                                    child:  BrnTagCustom.buildBorderTag(
                                      tagText: '电话联系',
                                      textColor: MyColors.themeColor,
                                      borderColor: MyColors.themeColor,
                                      fontWeight: FontWeight.w600,
                                      borderWidth: 1,
                                      fontSize: 12.sp,
                                      tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                      textPadding: EdgeInsets.all(6),
                                    ),
                                    onTap: (){
                                      _makePhoneCall(dataList[index]['phoneNum']);
                                    },
                                  ),
                                ],
                              ),
                            ),

                          ],
                        ),
                      ),
                      onTap: (){
                        Navigator.push( context, FadeRoute(page:DriverIntroduction(DrvId: dataList[index]['driverId'],)));
                      },
                    );

                  }
              ),
            )


              ],
            )
            )
          )
        ],
      ),
    );
  }
}
